import Layout from '@/layout'
import path from "path";

const userInfoKey = 'user_info'

export function getUserInfo() {
    return JSON.stringify(localStorage.getItem(userInfoKey))
}

export function setUserInfo(userInfo = {}) {
    return localStorage.setItem(userInfoKey, JSON.stringify(userInfo))
}

export function removeUserInfo() {
    return localStorage.removeItem(userInfoKey)
}


// 根据后台返回的数据过滤动态路由权限，dynamicRoutes本身就是递归的形式
export function filterDynamicRoutes(dynamicRoutes) {
    return dynamicRoutes.filter(route => {
        route.path = path.resolve(route.path)
        if (route.component) {
            // Layout 组件特殊处理
            if (route.component === 'Layout') {
                route.component = Layout
            } else {
                route.component = loadView(route.component)
            }
        }
        if (route.children && route.children.length) {
            route.children = filterDynamicRoutes(route.children)
        } else {
            delete route["children"]
        }
        return true
    })
}

// 错误原因是webpack打包逻辑，webpack4中动态import不支持变量方式
export const loadView = (view) => {
    if (process.env.NODE_ENV === 'development') {
        return (resolve) => require([`@/views/${view}`], resolve)
    } else {
        // 使用 import 实现生产环境的路由懒加载
        return () => import(`@/views/${view}`)
    }
}